package com.exam.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.achievement.dao.CourseRepository;
import com.achievement.entity.Course;
import com.alibaba.fastjson.JSONObject;
import com.common.util.TablePage;
import com.exam.dao.ExamRepository;
import com.exam.entity.Exam;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.mark.dao.StuAnswerRepository;
import com.mark.entity.StuAnswer;
import com.mark.entity.StuOptions;
import com.paper.dao.PaperRepository;
import com.paper.entity.Paper;
import com.paper.entity.Subtopics;
import com.paper.entity.Topics;
import com.user.dao.StudentRepository;
import com.user.entity.Student;
import com.user.entity.dto.StudentDTO;

@Service
@Transactional
public class ExamService implements IExamService {
	@Autowired
	private ExamRepository examDao;
	@Autowired
	private CourseRepository courseDao;
	@Autowired
	private PaperRepository paperDao;
	@Autowired
	private StuAnswerRepository stuAnswerDao;
	@Autowired
	private StudentRepository studentDao;

	@Override
	public TablePage<Exam> findPage(Specification<Exam> spec, Pageable pageable) {
		Page<Exam> page = examDao.findAll(spec, pageable);
		return TablePage.getTablePage(page);
	}

	@Override
	public void save(Exam exam) {
		// TODO Auto-generated method stub
		examDao.save(exam);
	}

	@Override
	public void cancel(Long id) {
		// TODO Auto-generated method stub
		Exam exam = examDao.findOne(id);
		exam.setDate(null);
		examDao.save(exam);
	}

	@Override
	public void publish(Exam exam) {
		// TODO Auto-generated method stub
		Date date = exam.getDate();
		Exam new_exam = examDao.findOne(exam.getId());
		
		new_exam.setDate(date);
		examDao.save(new_exam);
	}

	@Override
	public Exam findOne(Long id) {
		// TODO Auto-generated method stub
		return examDao.findOne(id);
	}

	@Override
	public Exam attendExam(Long stuId, Long eId) {
		// TODO Auto-generated method stub
		Exam exam = examDao.findOne(eId);
		StuAnswer stuAnswer = stuAnswerDao.findByStuAndExam(stuId, eId);
		if(null==exam)return null;
		Date now = new Date();
		Date date = exam.getDate();
		System.out.println("考试已开始:"+(now.getTime()-date.getTime()));
		if(null==stuAnswer) {
			
			Long past = now.getTime()-date.getTime();
			if(past/(60*1000)>30) {
				System.out.println("开考超过30分钟!");
				return null;
			}else {
				//新建考试
				Student student = studentDao.findOne(stuId);
				StuAnswer s = new StuAnswer();
				s.setExam(exam);
				s.setStudent(student);
				
				Paper paper = exam.getPaper();

				for(int i=0;i<paper.getTopics().size();i++) {
					Map<Integer, Subtopics> sublist = paper.getTopics().get(i+1).getSubtopics();
					for(int j=0;j<sublist.size();j++) {
						StuOptions stuOptions = new StuOptions();
						stuOptions.setSubtopics(sublist.get(j+1));
						s.getStuOptions().add(stuOptions);
					}
				}
				stuAnswerDao.save(s);
				return exam;
			}
		}else if((now.getTime()-date.getTime())/(1000*60)>exam.getPaper().getTime()) {
			System.out.println("考试结束!");
			return null;
		}else{
			return null;
		}
	}

	@Override
	public String startExam(HttpSession session, Long examId) {
		// TODO Auto-generated method stub
		//返回json格式:{'success':boolean,'msg','','paper':{},'stuAnswer':{}}
		
		String result = "";
		boolean success = false;
		Paper data = new Paper();
		
		/*
		 * 1.未登录
		 */
		StudentDTO dto = (StudentDTO) session.getAttribute("student");
		if(null==dto||null==dto.getId()) {
			return "{\"success\":false,\"msg\":\"未授权!\"}";
		}
		
		/*
		 * 2.考试信息空
		 */
		Exam exam = examDao.findOne(examId);
		if(null==exam)return "{\"success\":false,\"msg\"}";
		
		StuAnswer stuAnswer = stuAnswerDao.findByStuAndExam(dto.getId(), examId);
		Date now = new Date();
		Date date = exam.getDate();
		System.out.println("考试已开始:"+(now.getTime()-date.getTime()));
		
		if(null==stuAnswer) {
			
			Long past = now.getTime()-date.getTime();
			if(past/(60*1000)>30) {
				System.out.println("开考超过30分钟!");
				/*
				 * 3.考试开始超过30分钟，且考生未进入过考试。
				 */
				return "{\"success\":false,\"msg\":\"考试开始已超过30分钟，不能进入考试!\"}";
			}else if(past/(60*1000)<0){
				return "{\"success\":false,\"msg\":\"考试未开始!\"}";
			}else {
				/*
				 * 4.新建考试，新建答卷信息
				 */
				Student student = studentDao.findOne(dto.getId());
				StuAnswer s = new StuAnswer();
				s.setExam(exam);
				s.setStudent(student);
				
				Paper paper = exam.getPaper();

				for(int i=0;i<paper.getTopics().size();i++) {
					Map<Integer, Subtopics> sublist = paper.getTopics().get(i+1).getSubtopics();
					for(int j=0;j<sublist.size();j++) {
						StuOptions stuOptions = new StuOptions();
						stuOptions.setSubtopics(sublist.get(j+1));
						s.getStuOptions().add(stuOptions);
					}
				}
				
				stuAnswerDao.save(s);
				

				return "{\"success\":true,\"msg\":\"考试开始!\"}";
			}
		}else if((now.getTime()-date.getTime())/(1000*60)>exam.getPaper().getTime()) {
			System.out.println("考试结束!");
			/*
			 * 6.考试已结束
			 */
			return "{\"success\":false,\"msg\":\"考试已结束!\",\"data\":{}}";
		}else if(null!=stuAnswer){
			/*
			 * 5.重新加入考试
			 */
			if(stuAnswer.isCompleted())
				return "{\"success\":false,\"msg\":\"考生已交卷!\",\"data\":{}}";
			return "{\"success\":true,\"msg\":\"考试开始!\"}";
		}else{
			return "{\"success\":false,\"msg\":\"空！\",\"data\":{}}";
		}
	}

	@Override
	public boolean isNumExist(Exam exam) {
		// TODO Auto-generated method stub
		Exam e = examDao.findByNum(exam.getNum());
		if(e!=null&&e.getId()!=exam.getId())
			return true;
		return false;
	}

	@Override
	public boolean isRunningOrEnd(Long id) {
		// TODO Auto-generated method stub
		Exam exam = examDao.findOne(id);
		Date now = new Date();
		if(exam!=null&&now.getTime()>exam.getDate().getTime())
			return true;
		return false;
	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub
		examDao.delete(id);
	}

	@Override
	public Paper loadPaper(Long examId) {
		Exam exam = examDao.findOne(examId);
		Paper paper = exam.getPaper();
		return paper;
	}

	@Override
	public StuAnswer loadStuAnswer(Long stuId,Long examId) {
		// TODO Auto-generated method stub
		StuAnswer stuAnswer = stuAnswerDao.findByStuAndExam(stuId, examId);
		return stuAnswer;
	}

	@Override
	public Date getCurrentDate() {
		// TODO Auto-generated method stub
		Date now = new Date();
		return now;
	}
	
}
